﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using YasharEl.Infrastructure.Caching.Orm;
using YasharEl.Infrastructure.Caching.Configuration;
using YasharEl.Infrastructure.ObjectFactory;
using Microsoft.ApplicationServer.Caching;

namespace YasharEl.Infrastructure.Caching.AppFabric.Orm
{
    public class AppFabricOrmCacheManagerFactory : IOrmCacheManagerFactory
    {
        public IOrmCacheManager CreateAndRegisterCacheManager(OrmCacheManagerConfig ormCacheManagerConfig, IDependencyRegistrar dependencyRegistrar)
        {
            try
            {
                ISerializationProvider serializationProvider = null;
                if (ormCacheManagerConfig.SerializationProvider != null)
                {
                    serializationProvider = (ISerializationProvider)Activator.CreateInstance(ormCacheManagerConfig.SerializationProvider);
                }

                DataCacheFactory dataCacheFactory = new DataCacheFactory();

                DataCache ormDataCache = dataCacheFactory.GetCache(ormCacheManagerConfig.Name);

                DataCache ormLocksDataCache = dataCacheFactory.GetCache(ormCacheManagerConfig.OrmLocksRegionName);

                AppFabricOrmCacheManager appFabricOrmCacheManager = new AppFabricOrmCacheManager(
                    ormCacheManagerConfig.Name,
                    serializationProvider,
                    ormCacheManagerConfig.OrmRegionName,
                    ormCacheManagerConfig.OrmLocksRegionName,
                    (int)ormCacheManagerConfig.OrmLocksTimeout.TotalMilliseconds,
                    ormDataCache,
                    ormLocksDataCache
                );

                dependencyRegistrar.Register<IOrmCacheManager>(
                    appFabricOrmCacheManager,
                    ormCacheManagerConfig.Name,
                    true
                );

                return appFabricOrmCacheManager;
            }
            catch (Exception e)
            {
                throw new InvalidSystemConfigurationException("Orm cache manager not properly configured.", e);
            }
        }
    }
}
